package model

import (
	"fmt"
	"happy-sudoku/internal/sudoku"
	"io"

	"github.com/99designs/gqlgen/graphql"
)

// MarshalGridType marshal GridType
func MarshalGridType(g sudoku.GridType) graphql.Marshaler {
	return graphql.WriterFunc(func(w io.Writer) {
		d, err := g.Marshal()
		if err != nil {
			// !! TODO: Handle error
			print(err)
			return
		}
		w.Write([]byte("\"" + d + "\""))
	})
}

// UnmarshalGridType unmarsha grid
func UnmarshalGridType(vi interface{}) (sudoku.GridType, error) {
	v, ok := vi.(string)
	if !ok {
		return nil, fmt.Errorf("GridType: %T is not string", v)
	}

	res := sudoku.MakeGridType()
	err := res.Unmarshal(v)
	if err != nil {
		return nil, err
	}
	return res, nil
}

// UnmarshalInputGridType unmarsha grid
func UnmarshalInputGridType(vi interface{}) (sudoku.GridType, error) {
	return UnmarshalGridType(vi)
}
